<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>车辆检查管理</span>
        </div>
      </template>
      
      <!-- 搜索表单 -->
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
        <el-form-item label="车辆ID" prop="carId">
          <el-input v-model="queryParams.carId" placeholder="请输入车辆ID" clearable />
        </el-form-item>
        <el-form-item label="检查员" prop="inspector">
          <el-input v-model="queryParams.inspector" placeholder="请输入检查员" clearable />
        </el-form-item>
        <el-form-item label="检查结果" prop="result">
          <el-select v-model="queryParams.result" placeholder="请选择检查结果" clearable>
            <el-option label="通过" value="通过" />
            <el-option label="需维修" value="需维修" />
            <el-option label="不通过" value="不通过" />
          </el-select>
        </el-form-item>
        <el-form-item label="检查日期" prop="inspectionDate">
          <el-date-picker
            v-model="queryParams.inspectionDate"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 操作按钮区域 -->
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
        </el-col>
        <right-toolbar v-model:showSearch="showSearch" @refresh="getList"></right-toolbar>
      </el-row>

      <!-- 表格区域 -->
      <el-table v-loading="loading" :data="inspectionList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="检查ID" align="center" prop="inspectionId" />
        <el-table-column label="车辆信息" align="center">
          <template #default="scope">
            <div>ID: {{ scope.row.carId }}</div>
            <div>{{ scope.row.carNum }}</div>
            <div>{{ scope.row.carBrand }}</div>
          </template>
        </el-table-column>
        <el-table-column label="检查员" align="center" prop="inspector" />
        <el-table-column label="检查日期" align="center" prop="inspectionDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.inspectionDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="检查结果" align="center" prop="result">
          <template #default="scope">
            <el-tag :type="scope.row.result === '通过' ? 'success' : (scope.row.result === '需维修' ? 'warning' : 'danger')">
              {{ scope.row.result }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="报告" align="center" prop="reportUrl">
          <template #default="scope">
            <el-button v-if="scope.row.reportUrl" link type="primary" icon="Document" @click="viewReport(scope.row)">查看报告</el-button>
            <span v-else>无报告</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="View" @click="handleView(scope.row)">查看</el-button>
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        v-show="total > 0"
        :total="total"
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        @pagination="getList"
      />

      <!-- 添加或修改对话框 -->
      <el-dialog :title="title" v-model="open" width="700px" append-to-body>
        <el-form ref="inspectionForm" :model="form" :rules="rules" label-width="120px">
          <el-form-item label="车辆ID" prop="carId">
            <el-input v-model="form.carId" placeholder="请输入车辆ID" />
          </el-form-item>
          <el-form-item label="检查员" prop="inspector">
            <el-input v-model="form.inspector" placeholder="请输入检查员姓名" />
          </el-form-item>
          <el-form-item label="检查日期" prop="inspectionDate">
            <el-date-picker
              v-model="form.inspectionDate"
              type="datetime"
              placeholder="选择检查日期时间"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="外观状况" prop="exteriorCondition">
            <el-input v-model="form.exteriorCondition" type="textarea" rows="2" placeholder="请输入外观状况" />
          </el-form-item>
          <el-form-item label="内饰状况" prop="interiorCondition">
            <el-input v-model="form.interiorCondition" type="textarea" rows="2" placeholder="请输入内饰状况" />
          </el-form-item>
          <el-form-item label="机械状况" prop="mechanicalCondition">
            <el-input v-model="form.mechanicalCondition" type="textarea" rows="2" placeholder="请输入机械状况" />
          </el-form-item>
          <el-form-item label="电气状况" prop="electricalCondition">
            <el-input v-model="form.electricalCondition" type="textarea" rows="2" placeholder="请输入电气状况" />
          </el-form-item>
          <el-form-item label="报告URL" prop="reportUrl">
            <el-input v-model="form.reportUrl" placeholder="请输入报告URL" />
          </el-form-item>
          <el-form-item label="检查结果" prop="result">
            <el-select v-model="form.result" placeholder="请选择检查结果">
              <el-option label="通过" value="通过" />
              <el-option label="需维修" value="需维修" />
              <el-option label="不通过" value="不通过" />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" @click="submitForm">确 定</el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 查看详情对话框 -->
      <el-dialog title="检查详情" v-model="viewOpen" width="700px" append-to-body>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="检查ID">{{ viewData.inspectionId }}</el-descriptions-item>
          <el-descriptions-item label="车辆ID">{{ viewData.carId }}</el-descriptions-item>
          <el-descriptions-item label="车牌号">{{ viewData.carNum }}</el-descriptions-item>
          <el-descriptions-item label="车辆品牌">{{ viewData.carBrand }}</el-descriptions-item>
          <el-descriptions-item label="检查员">{{ viewData.inspector }}</el-descriptions-item>
          <el-descriptions-item label="检查日期">{{ parseTime(viewData.inspectionDate) }}</el-descriptions-item>
          <el-descriptions-item label="检查结果" :span="2">
            <el-tag :type="viewData.result === '通过' ? 'success' : (viewData.result === '需维修' ? 'warning' : 'danger')">
              {{ viewData.result }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="外观状况" :span="2">{{ viewData.exteriorCondition }}</el-descriptions-item>
          <el-descriptions-item label="内饰状况" :span="2">{{ viewData.interiorCondition }}</el-descriptions-item>
          <el-descriptions-item label="机械状况" :span="2">{{ viewData.mechanicalCondition }}</el-descriptions-item>
          <el-descriptions-item label="电气状况" :span="2">{{ viewData.electricalCondition }}</el-descriptions-item>
          <el-descriptions-item label="报告" :span="2">
            <el-button v-if="viewData.reportUrl" link type="primary" icon="Document" @click="viewReport(viewData)">查看报告</el-button>
            <span v-else>无报告</span>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间" :span="2">{{ parseTime(viewData.createTime) }}</el-descriptions-item>
        </el-descriptions>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getAllInspections, 
  getInspectionById, 
  addInspection,
  updateInspection, 
  deleteInspection, 
  searchInspections 
} from '@/api/inspection'

// 遮罩层
const loading = ref(false)
// 选中数组
const ids = ref([])
// 非单个禁用
const single = ref(true)
// 非多个禁用
const multiple = ref(true)
// 显示搜索条件
const showSearch = ref(true)
// 总条数
const total = ref(0)
// 车辆检查表格数据
const inspectionList = ref([])
// 弹出层标题
const title = ref("")
// 是否显示弹出层
const open = ref(false)
// 是否显示详情弹出层
const viewOpen = ref(false)
// 详情数据
const viewData = ref({})

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  carId: undefined,
  inspector: undefined,
  inspectionDate: undefined,
  result: undefined
})

// 表单参数
const form = reactive({
  inspectionId: undefined,
  carId: undefined,
  inspector: '',
  inspectionDate: undefined,
  exteriorCondition: '',
  interiorCondition: '',
  mechanicalCondition: '',
  electricalCondition: '',
  reportUrl: '',
  result: ''
})

// 表单校验
const rules = {
  carId: [
    { required: true, message: "车辆ID不能为空", trigger: "blur" }
  ],
  inspector: [
    { required: true, message: "检查员不能为空", trigger: "blur" }
  ],
  inspectionDate: [
    { required: true, message: "检查日期不能为空", trigger: "blur" }
  ],
  result: [
    { required: true, message: "检查结果不能为空", trigger: "blur" }
  ]
}

// 解析时间
const parseTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleString()
}

/** 查询检查记录列表 */
const getList = async () => {
  loading.value = true
  try {
    // 这里应该根据实际接口做分页处理，如果后端不支持，可以在前端处理
    // 这里简单处理，实际应该传入分页参数
    const response = await getAllInspections()
    inspectionList.value = response || []
    total.value = inspectionList.value.length
  } catch (error) {
    ElMessage.error("获取检查记录列表失败")
    console.error(error)
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = async () => {
  queryParams.pageNum = 1
  loading.value = true
  try {
    const response = await searchInspections(queryParams)
    inspectionList.value = response || []
    total.value = inspectionList.value.length
  } catch (error) {
    ElMessage.error("搜索检查记录失败")
    console.error(error)
  } finally {
    loading.value = false
  }
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.carId = undefined
  queryParams.inspector = undefined
  queryParams.inspectionDate = undefined
  queryParams.result = undefined
  handleQuery()
}

/** 多选框选中数据 */
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.inspectionId)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset()
  open.value = true
  title.value = "添加检查记录"
}

/** 查看按钮操作 */
const handleView = (row) => {
  viewData.value = row
  viewOpen.value = true
}

/** 查看报告操作 */
const viewReport = (row) => {
  if (!row.reportUrl) {
    ElMessage.warning('没有报告可查看')
    return
  }
  // 实际情况可能需要通过API请求获取报告内容或下载报告
  window.open(row.reportUrl, '_blank')
}

/** 修改按钮操作 */
const handleUpdate = async (row) => {
  reset()
  const inspectionId = row.inspectionId
  const response = await getInspectionById(inspectionId)
  if (!response) {
    ElMessage.error("获取检查记录信息失败")
    return
  }
  
  Object.assign(form, response)
  open.value = true
  title.value = "修改检查记录"
}

/** 提交按钮 */
const submitForm = async () => {
  const inspectionFormRef = ref(null)
  if (!inspectionFormRef.value) return
  
  try {
    await inspectionFormRef.value.validate()
    
    if (form.inspectionId) {
      // 修改
      await updateInspection(form)
      ElMessage.success("修改成功")
      open.value = false
      getList()
    } else {
      // 新增
      await addInspection(form)
      ElMessage.success("新增成功")
      open.value = false
      getList()
    }
  } catch (error) {
    ElMessage.error("操作失败")
    console.error(error)
  }
}

/** 删除按钮操作 */
const handleDelete = (row) => {
  const inspectionIds = row.inspectionId || ids.value
  if (!inspectionIds || (Array.isArray(inspectionIds) && !inspectionIds.length)) {
    ElMessage.warning("请选择要删除的检查记录")
    return
  }
  
  ElMessageBox.confirm('是否确认删除检查记录?', "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    try {
      // 如果是数组，需要循环删除，这里简单处理
      if (Array.isArray(inspectionIds)) {
        // 实际可能需要批量删除API
        for (const id of inspectionIds) {
          await deleteInspection(id)
        }
      } else {
        await deleteInspection(inspectionIds)
      }
      getList()
      ElMessage.success("删除成功")
    } catch (error) {
      ElMessage.error("删除失败")
      console.error(error)
    }
  }).catch(() => {})
}

/** 导出按钮操作 */
const handleExport = () => {
  // 实际导出功能，需要根据后端API进行调整
  ElMessage.info("导出功能开发中")
}

// 表单重置
const reset = () => {
  form.inspectionId = undefined
  form.carId = undefined
  form.inspector = ''
  form.inspectionDate = undefined
  form.exteriorCondition = ''
  form.interiorCondition = ''
  form.mechanicalCondition = ''
  form.electricalCondition = ''
  form.reportUrl = ''
  form.result = ''
}

/** 取消按钮 */
const cancel = () => {
  open.value = false
  reset()
}

// 初始化
onMounted(() => {
  getList()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.mb8 {
  margin-bottom: 8px;
}
</style> 